package com.codecrane.core.util;

import java.util.Map;

/**
 * 基于数组实现的权重随机工具类
 * Created by crane on 16/7/8.
 */
public class ArrayWeightRandom<T> extends WeightRandom<T> {
    private Object[] array;
    private int size;

    public ArrayWeightRandom(Map<T, Integer> data) {
        super(data);
    }

    @Override
    public void init() {
        int total = 0;
        for (Integer each : data.values()) {
            if (null != each) {
                total += each;
            }
        }
        array = new Object[total];
        int idx = 0;
        for (Map.Entry<T, Integer> each : data.entrySet()) {
            T key = each.getKey();
            Integer value = each.getValue();
            if (null != value && value > 0) {
                for (int i = 0; i < value; i++) {
                    array[idx++] = key;
                }
            }
        }
        size = total;
    }

    @Override
    public T random() {
        int idx = this.ran.nextInt(size);
        return random(idx);
    }

    @Override
    public T random(int ran) {
        if (ran < 0) {
            ran = -ran;
        }
        ran = ran % size;
        return (T) array[ran];
    }
}
